package com.distribute.framework.core.web.node;

import java.io.OutputStream;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletOutputStream;

import org.apache.poi.hssf.usermodel.*;

import com.distribute.framework.core.lang.Feflect;
import com.distribute.framework.core.lang.caption;
import com.distribute.framework.core.web.util.Page;

public abstract class Export {
	
		
	public abstract  Page getPage(Integer page, int querySize);	
	
	
	/**
	 * 数据导出功能
	 * @param count
	 * @param size
	 * @param export
	 * @param rootClass
	 * @param keyELs
	 * @throws Exception 
	 */
	public static void export(int maxCount,int querySize,int pageIndex,Export exporter,Class<?> rootClass,List<String> fieldExpressions) throws Exception{
		if(fieldExpressions==null || fieldExpressions.isEmpty()){
			fieldExpressions = new ArrayList();
			Field[] fields = rootClass.getDeclaredFields();
			for(Field field:fields){
				if(field.getAnnotation(caption.class)!=null)
					fieldExpressions.add(field.getName());
			}
		}
		
		//导出的页码转成（一次查询的数量）的页码范围
		int start = maxCount/querySize*pageIndex;
		int finish = maxCount/querySize*(pageIndex+1);
		
		javax.servlet.http.HttpServletResponse response = com.distribute.framework.core.xwork.WebContext.getServletResponse();
		response.setCharacterEncoding("UTF-8"); 
		OutputStream os = response.getOutputStream();
		response.setContentType("application/x-octet-stream");
		caption caption = rootClass.getAnnotation(caption.class);//获取类的描述注解
		response.setHeader("Content-Disposition", "attachment;filename="+java.net.URLEncoder.encode(caption==null ? "数据导出" :caption.value(),"UTF-8")+"."+pageIndex+".xls");
				
		
		//创建excel工作簿
		HSSFWorkbook workbook=new HSSFWorkbook();
		//创建工作表sheet
		HSSFSheet sheet=workbook.createSheet();
		//创建第一行
		HSSFRow row=sheet.createRow(0);
		row.setHeight((short)400);
		HSSFCell cell=null;
		//插入第一行数据的表头
		for(int i=0;i<fieldExpressions.size();i++){
			cell=row.createCell(i);
		    cell.setCellValue(Feflect.getFieldCaption(rootClass,fieldExpressions.get(i)));
		}
		int last = -1;
		int line = 1;
		for(int i=start;i<=finish;i++){
			Page page = exporter.getPage(i,querySize);
			if(page.getIndex()==last)
				break;
			last = page.getIndex();
			List list = page.getResult();
			for(int j=0;j<list.size();j++){
				Object item=list.get(j);
				HSSFRow nrow=sheet.createRow(line);	
				nrow.setHeight((short)400);
				for(int k=0;k<fieldExpressions.size();k++){
					HSSFCell ncell=nrow.createCell(k);
					ncell.setCellValue(Feflect.getFieldValue(item,fieldExpressions.get(k)));
				}
				line++;
			}
		}
		
		workbook.write(os);
		workbook.close();
		os.flush();
		os.close();
	}
	
}